package thumnailer

import (
	"fmt"
	"image"
	"image/gif"
	"image/jpeg"
	"image/png"
	"io"
	"os"
	"path"
	"strings"

	"github.com/disintegration/imaging"
	ants "github.com/panjf2000/ants/v2"
	log "github.com/sirupsen/logrus"
)

var p *ants.Pool

func Setup() {
	p, _ = ants.NewPool(10000)
}

func Close() {
	p.Release()
}

func copyFile(originPath string, outputPath string) error {
	// 读取文件
	file, err := os.Open(originPath)
	if err != nil {
		return err
	}

	defer file.Close()
	out, err := os.Create(outputPath)
	if err != nil {
		return err
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	return err
}

func AddTask(originPath string, outputPath string) {
	p.Submit(func() {
		if err := thumbnailify(originPath, outputPath); err != nil {
			// 复制原图片过去
			if e := copyFile(originPath, outputPath); e != nil {
				log.Errorln(e)
			}
			log.Errorln(err)
		}
		log.Debug("%s completed\n", originPath)
	})
}

func thumbnailify(originPath string, outputPath string) (err error) {
	var (
		file *os.File
		img  image.Image
	)

	extname := strings.ToLower(path.Ext(originPath))

	// 读取文件
	if file, err = os.Open(originPath); err != nil {
		return
	}

	defer file.Close()

	// decode jpeg into image.Image
	switch extname {
	case ".jpg", ".jpeg":
		img, err = jpeg.Decode(file)
	case ".png":
		img, err = png.Decode(file)
	case ".gif":
		img, err = gif.Decode(file)
	default:
		err = fmt.Errorf("Unsupport file type%s", extname)
		return
	}

	if img == nil {
		err = fmt.Errorf("Generate thumbnail fail...")
		return
	}
	m := imaging.Resize(img, 300, 0, imaging.NearestNeighbor)

	out, err := os.Create(outputPath)
	if err != nil {
		return
	}
	defer out.Close()

	// write new image to file

	//decode jpeg/png/gif into image.Image
	switch extname {
	case ".jpg", ".jpeg":
		jpeg.Encode(out, m, nil)
	case ".png":
		png.Encode(out, m)
	case ".gif":
		gif.Encode(out, m, nil)
	default:
		err = fmt.Errorf("Unsupport file type%s", extname)
		return
	}

	return
}
